package com.xyx.bloodoxygenjava.utils;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.UUID;

/* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtilityService.class */
public class ACSUtilityService extends Service {
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private static final String TAG = "ACSUtilityService";
    private String mBluetoothDeviceAddress;
    public BluetoothGatt mBluetoothGatt;
    private static final int STATE_DISCONNECTED = 0;
    public static final int EVENT_GATT_CONNECTED = 1;
    public static final int EVENT_GATT_DISCONNECTED = 2;
    public static final int EVENT_GATT_SERVICES_DISCOVERED = 3;
    public static final int EVENT_OPEN_PORT_SUCCEED = 4;
    public static final int EVENT_DATA_AVAILABLE = 5;
    public static final int EVENT_DATA_RECEIVED = 6;
    public static final int EVENT_HEART_BEAT_DEBUG = 7;
    public static final int EVENT_DATA_SEND_SUCEED = 8;
    public static final int EVENT_DATA_SEND_FAILED = 9;
    public static final String EXTRA_DATA = "EXTRA_DATA";
    private Handler mCurrentEventHandler;
    private WorkerThread workerThread;
    public static final UUID ACS_SERVICE_UUID = UUID.fromString("0000FFB0-0000-1000-8000-00805f9b34fb");
    public static final UUID CCC = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    private int mConnectionState = STATE_DISCONNECTED;
    private final UUID CMD_LINE_UUID = UUID.fromString("0000FFB1-0000-1000-8000-00805f9b34fb");
    private final UUID DATA_LINE_UUID = UUID.fromString("0000FFB2-0000-1000-8000-00805f9b34fb");
    private final int ACSUTILITY_SCAN_TIMEOUT_MSG = 1;
    private Stack<Handler> mEventHandlers = new Stack<>();
    private boolean isInitializing = true;
    private int packagesCount = STATE_DISCONNECTED;
    private ArrayList<byte[]> packages = new ArrayList<>();
    private int wakeTimes = STATE_DISCONNECTED;
    private IBinder binder = new ACSBinder();
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { // from class: com.bde.parentcyTransport.ACSUtilityService.1
        @Override // android.bluetooth.BluetoothGattCallback
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Message msg = null; //ACSUtilityService.STATE_DISCONNECTED
            Log.i(ACSUtilityService.TAG, "onConnectionStateChange " + newState + "  " + status);
            if (status != 0) {
                msg = ACSUtilityService.this.mCurrentEventHandler.obtainMessage(3);
            } else if (newState == 2) {
                ACSUtilityService.this.mConnectionState = 2;
                msg = ACSUtilityService.this.mCurrentEventHandler.obtainMessage(1);
                Log.i(ACSUtilityService.TAG, "Connected to GATT server.");
                Log.i(ACSUtilityService.TAG, "Attempting to start service discovery:" + ACSUtilityService.this.mBluetoothGatt.discoverServices());
            } else if (newState == 0) {
                ACSUtilityService.this.mConnectionState = ACSUtilityService.STATE_DISCONNECTED;
                Log.i(ACSUtilityService.TAG, "Disconnected from GATT server.");
                ACSUtilityService.this.close();
                msg = ACSUtilityService.this.mCurrentEventHandler.obtainMessage(2);
                ACSUtilityService.this.mBluetoothDeviceAddress = null;
                ACSUtilityService.this.isConnected = false;
            }
            msg.sendToTarget();
        }

        @Override // android.bluetooth.BluetoothGattCallback
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.i(ACSUtilityService.TAG, "Starting enable DATA Line Notificaiton");
            ACSUtilityService.this.setACSNotification(ACSUtilityService.this.CMD_LINE_UUID);
        }

        @Override // android.bluetooth.BluetoothGattCallback
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.i(ACSUtilityService.TAG, "onCharacteristicRead " + status);
        }

        @Override // android.bluetooth.BluetoothGattCallback
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            byte[] value = characteristic.getValue();
            Message msg = null;//ACSUtilityService.STATE_DISCONNECTED;
            if (characteristic.getUuid().equals(ACSUtilityService.this.CMD_LINE_UUID)) {
                if (value[ACSUtilityService.STATE_DISCONNECTED] == 5) {
                    Log.i(ACSUtilityService.TAG, "heart beat package write back ");
                    msg = ACSUtilityService.this.mCurrentEventHandler.obtainMessage(7);
                    characteristic.setValue(new byte[]{5});
                    ACSUtilityService.this.mBluetoothGatt.writeCharacteristic(characteristic);
                }
            } else if (characteristic.getUuid().equals(ACSUtilityService.this.DATA_LINE_UUID)) {
                LogCat.d(ACSUtilityService.TAG, "data line : length = " + value.length);
                LogCat.d(ACSUtilityService.TAG, "接收到数据  " + Arrays.toString(characteristic.getValue()));
                msg = ACSUtilityService.this.mCurrentEventHandler.obtainMessage(5);
                Bundle bundle = new Bundle();
                bundle.putByteArray(ACSUtilityService.EXTRA_DATA, characteristic.getValue());
                msg.setData(bundle);
            }
            msg.sendToTarget();
        }

        public void enablePhoneMode() {
            LogCat.i(ACSUtilityService.TAG, "Enabling Phone Mode...");
            BluetoothGattCharacteristic characCMD = ACSUtilityService.this.getACSCharacteristic(ACSUtilityService.this.CMD_LINE_UUID);
            if (characCMD == null) {
                LogCat.i(ACSUtilityService.TAG, "characCMD == null");
                return;
            }
            characCMD.setValue(new byte[]{6, 1});
            ACSUtilityService.this.mBluetoothGatt.writeCharacteristic(characCMD);
        }

        /* JADX WARN: Multi-variable type inference failed */
        /* JADX WARN: Type inference failed for: r0v18, types: [com.bde.parentcyTransport.ACSUtilityService$WorkerThread] */
        /* JADX WARN: Type inference failed for: r0v19, types: [java.lang.Throwable] */
        /* JADX WARN: Type inference failed for: r0v25 */
        /* JADX WARN: Unknown variable types count: 1 */
        @Override // android.bluetooth.BluetoothGattCallback
        /*
            Code decompiled incorrectly, please refer to instructions dump.
            To view partially-correct code enable 'Show inconsistent code' option in preferences
        */
        public void onCharacteristicWrite(android.bluetooth.BluetoothGatt r6, android.bluetooth.BluetoothGattCharacteristic r7, int r8) {
            /*
                Method dump skipped, instructions count: 242
                To view this dump change 'Code comments level' option to 'DEBUG'
            */
            throw new UnsupportedOperationException("Method not decompiled: com.bde.parentcyTransport.ACSUtilityService.AnonymousClass1.onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int):void");
        }

        @Override // android.bluetooth.BluetoothGattCallback
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
            Log.i(ACSUtilityService.TAG, "onDescriptorWrite " + status);
            if (status == 0) {
                Log.i(ACSUtilityService.TAG, descriptor.getCharacteristic().getUuid() + " Notification Enabled");
            }
            if (descriptor.getCharacteristic().getUuid().equals(ACSUtilityService.this.DATA_LINE_UUID)) {
                ACSUtilityService.this.isInitializing = false;
                ACSUtilityService.this.mCurrentEventHandler.obtainMessage(4).sendToTarget();
                ACSUtilityService.this.isConnected = true;
            } else if (descriptor.getCharacteristic().getUuid().equals(ACSUtilityService.this.CMD_LINE_UUID)) {
                Log.i(ACSUtilityService.TAG, "Starting enable DATA Line Notificaiton");
                ACSUtilityService.this.mCurrentEventHandler.postDelayed(new Runnable() { // from class: com.bde.parentcyTransport.ACSUtilityService.1.1
                    @Override // java.lang.Runnable
                    public void run() {
                        ACSUtilityService.this.setACSNotification(ACSUtilityService.this.DATA_LINE_UUID);
                    }
                }, 2000);
            }
        }
    };
    private boolean isConnected = false;

    static /* synthetic */ Handler access$0(ACSUtilityService aCSUtilityService) {
        return aCSUtilityService.mCurrentEventHandler;
    }

    static /* synthetic */ int access$13(ACSUtilityService aCSUtilityService) {
        return aCSUtilityService.packagesCount;
    }

    static /* synthetic */ void access$16(ACSUtilityService aCSUtilityService, int i) {
        aCSUtilityService.packagesCount = i;
    }

    static /* synthetic */ ArrayList access$14(ACSUtilityService aCSUtilityService) {
        return aCSUtilityService.packages;
    }

    static /* synthetic */ int access$11(ACSUtilityService aCSUtilityService) {
        return aCSUtilityService.wakeTimes;
    }

    static /* synthetic */ void access$12(ACSUtilityService aCSUtilityService, int i) {
        aCSUtilityService.wakeTimes = i;
    }

    public void addEventHandler(Handler eventHandler) {
        this.mEventHandlers.push(eventHandler);
        this.mCurrentEventHandler = eventHandler;
    }

    public void removeEventHandler() {
        this.mEventHandlers.pop();
        if (!this.mEventHandlers.empty()) {
            this.mCurrentEventHandler = this.mEventHandlers.peek();
        }
    }

    /* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtilityService$ACSBinder.class */
    public class ACSBinder extends Binder {
        public ACSBinder() {
        }

        public ACSUtilityService getService() {
            return ACSUtilityService.this;
        }
    }

    @Override // android.app.Service
    public IBinder onBind(Intent intent) {
        return this.binder;
    }

    @Override // android.app.Service
    public boolean onUnbind(Intent intent) {
        LogCat.i(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override // android.app.Service
    public void onCreate() {
        super.onCreate();
        this.isInitializing = true;
        LogCat.logToFileInit();
    }

    private void enablePhoneMode() {
        LogCat.i(TAG, "Enabling Phone Mode...");
        if (this.mBluetoothGatt == null) {
            LogCat.i(TAG, "mBtGatt == null");
        }
        BluetoothGattService disService = this.mBluetoothGatt.getService(ACS_SERVICE_UUID);
        if (disService == null) {
            LogCat.i(TAG, "disService == null");
            return;
        }
        BluetoothGattCharacteristic characCMD = disService.getCharacteristic(this.CMD_LINE_UUID);
        if (characCMD == null) {
            LogCat.i(TAG, "characCMD == null");
            return;
        }
        characCMD.setValue(new byte[]{6, 1});
        this.mBluetoothGatt.writeCharacteristic(characCMD);
    }

    public boolean initialize() {
        Log.i(TAG, "Initializing ");
        if (this.mBluetoothManager == null) {
            this.mBluetoothManager = (BluetoothManager) getSystemService("bluetooth");
            if (this.mBluetoothManager == null) {
                Log.i(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }
        this.mBluetoothAdapter = this.mBluetoothManager.getAdapter();
        if (this.mBluetoothAdapter != null) {
            return true;
        }
        Log.i(TAG, "Unable to obtain a BluetoothAdapter.");
        return false;
    }

    public boolean connect(String address) {
        if (this.mBluetoothAdapter == null || address == null || !BluetoothAdapter.checkBluetoothAddress(address)) {
            Log.i(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }
        BluetoothDevice device = this.mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.i(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        if (this.mBluetoothGatt != null) {
            this.mBluetoothGatt.close();
            this.mBluetoothGatt = null;
        }
        this.mBluetoothGatt = device.connectGatt(this, false, this.mGattCallback);
        Log.i(TAG, "Trying to create a new connection.");
        this.mBluetoothDeviceAddress = address;
        this.mConnectionState = 1;
        return true;
    }

    public void disconnect() {
        try {
            if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
                Log.i(TAG, "BluetoothAdapter not initialized");
                return;
            }
            this.mBluetoothGatt.disconnect();
            this.workerThread = null;
            this.isConnected = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        if (this.mBluetoothGatt != null) {
            this.isConnected = false;
            this.mBluetoothGatt.close();
            this.mBluetoothGatt = null;
        }
    }

    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
            Log.i(TAG, "BluetoothAdapter not initialized");
        } else {
            this.mBluetoothGatt.readCharacteristic(characteristic);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public boolean setACSNotification(UUID charaUUID) {
        if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
            Log.i(TAG, "BluetoothAdapter not initialized");
            return false;
        }
        BluetoothGattCharacteristic chara = getACSCharacteristic(charaUUID);
        if (chara != null) {
            return setCharacteristicNotification(chara, true);
        }
        Log.i(TAG, "Characteristic is null!");
        Log.i(TAG, "Enableing Notification failed!");
        return false;
    }

    private boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
            Log.i(TAG, "BluetoothAdapter not initialized");
            return false;
        }
        this.mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        return this.mBluetoothGatt.writeDescriptor(descriptor);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public BluetoothGattCharacteristic getACSCharacteristic(UUID charaUUID) {
        if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
            Log.i(TAG, "BluetoothAdapter not initialized");
            return null;
        }
        BluetoothGattService service = this.mBluetoothGatt.getService(ACS_SERVICE_UUID);
        if (service != null) {
            return service.getCharacteristic(charaUUID);
        }
        Log.i(TAG, "Service is not found!");
        return null;
    }

    public boolean writePort(byte[] value) {
        byte[] blePackage;
        if (this.mBluetoothGatt == null || !this.isConnected) {
            return false;
        }
        int rest = value.length;
        int count = STATE_DISCONNECTED;
        while (rest > 0) {
            rest -= 20;
            if (rest >= 0) {
                blePackage = new byte[20];
                for (int j = STATE_DISCONNECTED; j < 20; j++) {
                    blePackage[j] = value[j + (count * 20)];
                }
            } else {
                int rest2 = rest + 20;
                blePackage = new byte[rest2];
                for (int j2 = STATE_DISCONNECTED; j2 < rest2; j2++) {
                    blePackage[j2] = value[j2 + (count * 20)];
                }
                rest = rest2 - 20;
            }
            this.packages.add(blePackage);
            count++;
        }
        this.packagesCount = (value.length / 20) + (value.length % 20 > 0 ? 1 : STATE_DISCONNECTED);
        this.workerThread = new WorkerThread();
        this.workerThread.start();
        return true;
    }

    static /* synthetic */ boolean access$15(ACSUtilityService aCSUtilityService, byte[] bArr) {
        return aCSUtilityService.writePackage(bArr);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public boolean writePackage(byte[] value) {
        LogCat.d(TAG, "writePort 1");
        try {
            if (this.mBluetoothGatt == null) {
                Log.i(TAG, "writePackage mBluetoothGatt == null");
                return false;
            }
            LogCat.d(TAG, "writePort 2");
            BluetoothGattService ACSService = this.mBluetoothGatt.getService(ACS_SERVICE_UUID);
            if (ACSService == null) {
                Log.i(TAG, "writePackage ACSService == null");
                return false;
            }
            LogCat.d(TAG, "writePort 3");
            BluetoothGattCharacteristic characteristic = ACSService.getCharacteristic(this.DATA_LINE_UUID);
            if (characteristic == null) {
                Log.i(TAG, "writePackage characteristic == null");
                return false;
            }
            characteristic.setValue(value);
            LogCat.d(TAG, "writePort 4");
            return this.mBluetoothGatt.writeCharacteristic(characteristic);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<BluetoothGattService> getSupportedGattServices() {
        if (this.mBluetoothGatt == null) {
            return null;
        }
        return this.mBluetoothGatt.getServices();
    }

    @Override // android.app.Service
    public void onDestroy() {
        super.onDestroy();
        LogCat.logToFileFini();
    }

    /* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtilityService$WorkerThread.class */
    class WorkerThread extends Thread {
        private int operationResult = ACSUtilityService.STATE_DISCONNECTED;
        private int repeatSendTimes = ACSUtilityService.STATE_DISCONNECTED;

        WorkerThread() {
        }

        public int getOperationResult() {
            return this.operationResult;
        }

        public void setOperationResult(int operationResult) {
            this.operationResult = operationResult;
        }

        /*  JADX ERROR: JadxRuntimeException in pass: BlockProcessor
            jadx.core.utils.exceptions.JadxRuntimeException: Unreachable block: B:24:0x00b8
            	at jadx.core.dex.visitors.blocks.BlockProcessor.checkForUnreachableBlocks(BlockProcessor.java:86)
            	at jadx.core.dex.visitors.blocks.BlockProcessor.processBlocksTree(BlockProcessor.java:52)
            	at jadx.core.dex.visitors.blocks.BlockProcessor.visit(BlockProcessor.java:44)
            */
        @Override // java.lang.Thread, java.lang.Runnable
        public void run() {
            /*
                Method dump skipped, instructions count: 324
                To view this dump change 'Code comments level' option to 'DEBUG'
            */
            throw new UnsupportedOperationException("Method not decompiled: com.bde.parentcyTransport.ACSUtilityService.WorkerThread.run():void");
        }
    }

    public void sendOver() {
        this.packagesCount = STATE_DISCONNECTED;
        this.workerThread = null;
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtilityService$LogCat.class */
    public static class LogCat {
        static BufferedOutputStream bos;

        private LogCat() {
        }

        public static void logToFileInit() {
            try {
                bos = new BufferedOutputStream(new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "Log.txt")));
            } catch (FileNotFoundException e) {
                Log.e(ACSUtilityService.TAG, "FileNotFoundException");
                e.printStackTrace();
            }
        }

        public static void logToFileFini() {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
            } catch (IOException e) {
                Log.e(ACSUtilityService.TAG, "flush failed or close failed");
                e.printStackTrace();
            }
        }

        private static void logToFile(String tag, String message) {
            if (bos != null) {
                StringBuilder sb = new StringBuilder(tag);
                sb.append("   " + message + "\n");
                try {
                    bos.write(sb.substring(ACSUtilityService.STATE_DISCONNECTED).getBytes());
                } catch (IOException e) {
                    Log.e(ACSUtilityService.TAG, "write failed");
                    e.printStackTrace();
                }
            }
        }

        public static int v(String tag, String msg) {
            logToFile(tag, msg);
            return Log.v(tag, msg);
        }

        public static int i(String tag, String msg) {
            logToFile(tag, msg);
            return Log.i(tag, msg);
        }

        public static int e(String tag, String msg) {
            logToFile(tag, msg);
            return Log.e(tag, msg);
        }

        public static int d(String tag, String msg) {
            logToFile(tag, msg);
            return Log.d(tag, msg);
        }

        public static int w(String tag, String msg) {
            logToFile(tag, msg);
            return Log.w(tag, msg);
        }
    }
}